import {
	baseUrl
} from "../config/env";
import store from "../store";

/**
 * 上传图片
 * @param {Number} count 单次可选数量
 */
const uploadPics = (count = 1) => {
	let requestPicUrlList = []
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			sizeType: ['compressed'],
			success: chooseImageRes => {
				uni.showLoading({
					title: '上传中...'
				})
				const tempFilePaths = chooseImageRes.tempFilePaths;
				tempFilePaths.map(item => {
					uploadFile(item).then(url => {
						requestPicUrlList.push(url)
						if (tempFilePaths.length === requestPicUrlList.length) {
							uni.hideLoading()
							resolve(requestPicUrlList)
						}
					}).catch(() => {
						reject()
					});
				});
			},
			fail: (err) => {
				reject(err)
			}
		});
	})
}

const uploadVideo = ({
	sourceType = ['album', 'camera'],
	extension = [],
	compressed = false,
	maxDuration = 60,
	camera = 'back'
} = {}) => {
	return new Promise((resolve, reject) => {
		uni.chooseVideo({
			sourceType,
			extension,
			compressed,
			maxDuration,
			camera,
			success: (res) => {
				uni.showLoading({
					title: '上传中...'
				})
				uploadFile(res.tempFilePath).then(url => {
					uni.hideLoading()
					resolve(url)
				}).catch(() => {
					reject()
				});
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

const uploadFile = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `${baseUrl}/master/oss/upload`, //仅为示例，非真实的接口地址
			filePath,
			header: {
				token: store.getters.access_token
			},
			name: 'file',
			success: uploadFileRes => {
				resolve(JSON.parse(uploadFileRes.data).data)
			},
			fail: err => {
				uni.showToast({
					title: err.data.message || err,
					icon: 'none'
				});
				reject()
			}
		});
	})

}
export {
	uploadPics, uploadVideo
}
